<template>
	<view class="search-wrapper">
		<uni-search-bar class="uni-mt-10" radius="30" placeholder="输入城市名搜索" clearButton="auto" cancelButton="none" @confirm="search" />
	</view>
	<view class="t-index-address">
		<scroll-view class="t-index-address__scroll-view" :scroll-into-view="scrollview" :scroll-y="true"
			:enable-flex="true">
      <!-- 当前定位/最近访问 -->
      <view class="header-wrapper">
        <view class="location">
          <view class="sm-title"><text>当前定位</text></view>
          <view class="city-wrapper locate-wrapper">
            <view class="city-item"><image class="dw-icon" src="/static/icons/dw.svg" mode=""></image><text>{{currentLocate}}</text></view>
            <view class="locate-text">
              <uni-icons type="loop" size="16" color="#999"></uni-icons>
              <text @click="getLocate">重新定位</text>
            </view>
          </view>
        </view>
       <view class="location">
          <view class="sm-title"><text>热门城市</text></view>
            <view class="city-wrapper hot-city">
                <view class="city-item" @click="hotClick(item.initial , item.name)" v-for="item in hotCityList"  :key="item.name"  ><text>{{item.name}}</text></view>
             </view>
        </view>
      </view>
      
			<view :id="group.initial" v-for="group in cityList" :key="group.initial">
				<view class="t-index-address__anchor">
					<text>{{ group.initial }}</text>
				</view>
				<view class="t-index-address__list">
					<view class="t-index-address__cell" hover-class="list-hover" v-for="(city, index) in group.list" :key="index"
						 @click="select(city)">
						<text>{{ city.name }}</text>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="t-index-address__sidebar">
			<view class="t-index-address__index" v-for="group in cityList" :key="group.initial"
				@touchstart.stop.prevent="onTouchMove(group.initial)" @touchend.stop.prevent="onTouchStop"
				@touchcancel.stop.prevent="onTouchStop">
				<span>{{ group.initial }}</span>
			</view>
		</view>
		<view class="t-index-address__alert" v-if="touchmove">
			<text>{{ activeIndex }}</text>
		</view>
	</view>
</template>

<script>
	import cityList from "./cities.json";
    import amap from '@/common/amap-wx.js';//module.exports.AMapWX=AMapWX; 
	export default {
		data() {
			return {
				//key: 'cb487fe9d1b61791aebee44ab3f6a62a', //高德key
				key: '4d92f0669984f173ad035cd6bacd21c8', //高德key
				amapPlugin: null,
				scrollview: "A",
				cityList: [],
				activeIndex: "A",
				touchmove: false,
				currentLocate: '',
				code: '',
				hotCityList:[{"initial":"S","name":"上海"},{"initial":"B","name":"北京"},{"initial":"H","name":"杭州"},{"initial":"G","name":"广州"},{"initial":"S","name":"深圳"},{"initial":"W","name":"武汉"},{"initial":"N","name":"南京"},{"initial":"C","name":"成都"},{"initial":"Z","name":"重庆"}]
			};
		},
		watch: {
			activeIndex(value) {
				this.scrollview = value;
			},
		},
		methods: {
			hotClick(initial, name){
				for(var i = 0; i < this.cityList.length; i++) {
					if(this.cityList[i].initial == initial) {
						for(var j = 0; j < this.cityList[i].list.length; j++) {
							if (this.cityList[i].list[j].name == name){
								this.currentLocate = name;
								uni.setStorageSync('userLocation', this.cityList[i].list[j].lng + ','+ this.cityList[i].list[j].lat);
								this.code = this.cityList[i].list[j].code
								this.choose();
							}
						}
					}
				}
			},
			initCityList() {
				this.cityList = cityList;
			},
			select(data){
				this.currentLocate = data.name;
				uni.setStorageSync('currentLocate', data.name);
				uni.setStorageSync('userLocation', data.lng + ','+ data.lat);
				uni.navigateBack({
				    delta: 1
				});
			},
			search(cname){
				uni.request({
				    url: 'https://restapi.amap.com/v3/geocode/geo?key=cca999ed25a087f939cab0756c25ab9f&address=' + cname.value, //仅为示例，并非真实接口地址。
				    success: (res) => {
						if(res.data.status ==1) {
							var info = res.data.geocodes[0];
							this.currentLocate = cname.value;
							uni.setStorageSync('userLocation', info.location);
							uni.setStorageSync('currentLocate', cname.value);
							this.code = info.citycode;
							uni.navigateBack({
							    delta: 1
							});
						}else{
							uni.showToast({
								title: '未搜索到结果，请确认输入',
								icon: 'none'
							})
							return
						}
				    }
				});
			},
			getLocate() {
				this.amapPlugin = new amap.AMapWX({
					key: this.key
				});
				this.amapPlugin.getRegeo({
					success: (data) => {
					  const { addressComponent } = data[0].regeocodeData
					  this.currentLocate = addressComponent.province;
					  uni.setStorageSync('currentLocate', this.currentLocate);
					  this.code = addressComponent.adcode
					  this.choose();
					}
				});
			},
			onTouchMove(index) {
				this.activeIndex = index;
				this.touchmove = true;
			},
			onTouchStop() {
				this.touchmove = false;
			},
      //选择定位城市
      choose() {
        this.filterCity()
        Promise.resolve(
         this.filterCity()
        ).then(res => {
		  this.currentLocate = res.name
          this.$emit('select', res);
		  uni.navigateBack({
		      delta: 1
		  });
		  // uni.switchTab({
		  // 	url: '/pages/activity/index'
		  // })
        })
      },
      // 筛选城市
      filterCity() {
        let city = {}
        for (let s of cityList) {
          for (let item of s.list) {
            const i = this.code.indexOf(item.code)
            if(i != -1) {
              city = item
            }
          }
        }
        return city
      }
		},
		mounted() {
			this.initCityList();
			// 获取用户地理位置
			this.currentLocate = uni.getStorageSync('currentLocate') || "";
			if (this.currentLocate  === ""){
				this.getLocate();
			}
			
		},
	};
</script>

<style lang="scss" scoped>
	.t-index-address {
		height: 100%;
    
    .location{
      padding: 24rpx 30rpx;
      .sm-title{
        font-size: 14px;
        color: #666;
        margin-bottom: 12px;
      }
      .city-wrapper{
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        .city-item{
          // background-color: #f0f0f0;
          border-radius: 8rpx;
          border: 1px solid #F5F5F5;
					height: 60rpx;
					line-height: 60rpx;
          font-size: 15px;
          margin-right: 24rpx;
					margin-bottom: 16rpx;
					width: 180rpx;
					text-align: center;
        }
      }
      
      .locate-wrapper{
        justify-content: space-between;
        .locate-text{
          display: flex;
          align-items: center;
          font-size: 14px;
          color: #666;
        }
      }
			
			.hot-city {
				// width: calc(100% - 110rpx);
			}
    }

		&__scroll-view {
			width: 100%;
			height: 100%;
			max-height: 100vh;
		}

		&__anchor {
			padding: 15rpx 30rpx;
			width: 100%;
			font-size: 28rpx;
			font-weight: 500;
			color: #606266;
			background-color: rgb(245, 245, 245);
		}

		&__list {
			// padding: 0 30rpx 0 30rpx;
		}

		&__cell {
      padding: 0 30rpx;
			height: 100rpx;
			line-height: 100rpx;
			border-bottom: 1rpx solid #f2f2f2;
      font-size: 15px;

			&:last-child {
				border: none;
			}
		}

		&__sidebar {
			position: fixed;
			top: 50%;
			right: 0;
			transform: translateY(-50%);
			z-index: 99;
		}

		&__index {
			padding: 10rpx 20rpx;
			font-size: 22rpx;
			font-weight: 500;
			line-height: 1;
		}

		&__alert {
			position: fixed;
			top: 50%;
			right: 90rpx;
			z-index: 99;
			margin-top: -60rpx;
			width: 120rpx;
			height: 120rpx;
			font-size: 50rpx;
			color: #fff;
			border-radius: 24rpx;
			background-color: rgba(0, 0, 0, 0.5);
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
  .list-hover{
    background-color: #f0f0f0;
  }
  .dw-icon {
  	width: 24rpx;
  	height: 24rpx;
  	margin-left: 8rpx;
	margin-right: 8rpx;
  }
</style>
<style>
  @media (prefers-color-scheme: dark) {
    .header-wrapper, .t-index-address__list{
      background-color: #222 !important;
    }
    .t-index-address__cell{
      border-color: #333 !important;
    }
    .list-hover{
      background-color: #333 !important;
    }
    .city-item{
      background-color: #333 !important;
    }
    .sm-title, .locate-text{
      color: #f0f0f0 !important;
    }
    .t-index-address__anchor{
      color: #f0f0f0;
      background-color: #333 !important;
    }
  }
</style>
